<!DOCTYPE html>
<html>

<head>

</head>

<body>
    <script>
        // 难点是判断方括号对
        let str = '2[1[a]3[bee]2[3[c]4[d]]]'
        function smartReapt(templateStr) {
            const charStack = []
            const numberStack = []
            let rest = templateStr

            let index = 0
            while (index < templateStr.length - 1) {
                // const item = templateStr[index]
                rest = templateStr.substring(index)
                // 是不是数字和[开头
                if (/^\d+\[/.test(rest)) {
                    // (\d+)捕获数字
                    let times = Number(rest.match(/^(\d+)\[/)[1])
                    // +1 是方括号
                    index += times.toString().length + 1
                    numberStack.push(times)
                    charStack.push('')
                } else if(/^\w+\]/.test(rest)){
                    // 修改字符串栈顶
                    let word = rest.match(/^(\w+)\]/)[1]
                    charStack[charStack.length-1] = word
                    index+= word.length
                }else if(rest[0] === ']'){
                    // ] 弹栈
                    const times = numberStack.pop()
                    const word = charStack.pop()
                    charStack[charStack.length - 1] += word.repeat(times)
                    index ++
                }
            }
            return charStack[0].repeat(numberStack[0])
        }
        console.log(smartReapt(str))
    </script>
</body>

</html>